package com.myrn.sp

import android.content.Context
import android.content.SharedPreferences
import com.facebook.react.bridge.Callback
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactContextBaseJavaModule
import com.facebook.react.bridge.ReactMethod
import com.facebook.react.bridge.ReadableArray
import com.facebook.react.bridge.WritableArray
import com.facebook.react.bridge.WritableNativeArray

class SpModule(context: ReactApplicationContext) : ReactContextBaseJavaModule(context) {

    private val sp = context.getSharedPreferences("myrn", Context.MODE_PRIVATE)

    override fun getName(): String {
        return "SpModule"
    }

    @ReactMethod
    fun setStringValue(key: String, value: String) {
        with(sp.edit()) {
            putString(key, value)
            apply()
        }
    }

    @ReactMethod
    fun getStringValue(key: String): String {
        return sp.getString(key, "") ?: ""
    }

    @ReactMethod
    fun getStringSet(key: String, callback: Callback): WritableArray {
        val array: WritableArray = WritableNativeArray()
        sp.getStringSet(key, setOf())?.forEach {
            array.pushString(it)
        }
        callback.invoke(array)
        return array
    }

    @ReactMethod
    fun setStringSet(key: String?, value: ReadableArray?) {
        val set = mutableSetOf<String?>()
        value?.toArrayList()?.forEach {
            set.add(it as? String)
        }
        sp.edit().putStringSet(key, set).apply()
    }

//    @ReactMethod
//    fun getStringSet(key: String?): WritableArray {
//        return HashSet<String>(sp.getStringSet(key, HashSet<String>()))
//    }

}